import axios from 'axios';
import CryptoJS from 'crypto-js';

// 容联云配置（测试环境）
const RONG_LIAN_CONFIG = {
    accountSid: '2c94811c9860a9c401989ba2e2c40a4e',  // 主账号
    authToken: '399070f21f994a5bb68b875c2bbfa192',   // 主账号令牌
    appId: '2c94811c9860a9c401989ba2e4a20a55',       // 应用ID
    serverURL: 'https://app.cloopen.com:8883'        // 测试环境URL 
};

// 存储验证码（生产环境用Redis等存储）
const codeStore = new Map(); // key: 手机号, value: { code, expire }

// 生成容联云签名
const generateSignature = () => {
  const date = new Date();
  const timestamp = date.getFullYear().toString() +
      (date.getMonth() + 1).toString().padStart(2, '0') +
      date.getDate().toString().padStart(2, '0') +
      date.getHours().toString().padStart(2, '0') +
      date.getMinutes().toString().padStart(2, '0') +
      date.getSeconds().toString().padStart(2, '0');
  const sig = RONG_LIAN_CONFIG.accountSid + RONG_LIAN_CONFIG.authToken + timestamp;
  const signature = CryptoJS.MD5(sig).toString().toUpperCase();
  
  return { timestamp, signature };
};

// 发送短信验证码
export const sendSMS = async (phone) => {
  console.log('=== 发送短信请求开始 ===');
  console.log('请求参数:', { phone });

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    throw new Error('手机号格式不正确');
  }

  // 生成4位验证码
  const code = Math.floor(1000 + Math.random() * 9000).toString();
  console.log('生成的验证码:', code);
  
  // 存储验证码（有效期5分钟）
  codeStore.set(phone, {
    code,
    expire: Date.now() + 5 * 60 * 1000
  });

  const { timestamp, signature } = generateSignature();

  console.log('容联云配置:', {
    accountSid: RONG_LIAN_CONFIG.accountSid,
    appId: RONG_LIAN_CONFIG.appId,
    timestamp,
    signature
  });

  // 调用容联云API发送短信
  const url = `${RONG_LIAN_CONFIG.serverURL}/2013-12-26/Accounts/${RONG_LIAN_CONFIG.accountSid}/SMS/TemplateSMS?sig=${signature}`;
  
  const requestData = {
    to: phone,
    appId: RONG_LIAN_CONFIG.appId,
    templateId: '1',
    datas: [code]
  };
  
  console.log('容联云API请求URL:', url);
  console.log('容联云API请求数据:', requestData);

  const response = await axios.post(url, requestData, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': Buffer.from(`${RONG_LIAN_CONFIG.accountSid}:${timestamp}`).toString('base64')
    }
  });

  console.log('容联云API响应状态:', response.status);
  console.log('容联云API响应数据:', response.data);

  if (response.data.statusCode === '000000') {
    return { success: true, message: '验证码发送成功' };
  } else {
    console.error('容联云API错误详情:', response.data);
    throw new Error(`发送失败: ${response.data.statusMsg}`);
  }
};

// 验证短信验证码
export const verifySMSCode = (phone, code) => {
  const stored = codeStore.get(phone);
  if (!stored) {
    return { success: false, message: '请先获取验证码' };
  }

  if (Date.now() > stored.expire) {
    codeStore.delete(phone); // 清除过期验证码
    return { success: false, message: '验证码已过期' };
  }

  if (code !== stored.code) {
    return { success: false, message: '验证码不正确' };
  }

  // 验证成功
  codeStore.delete(phone); // 验证成功后清除验证码
  return { success: true, message: '验证成功' };
};

// 清除验证码
export const clearSMSCode = (phone) => {
  codeStore.delete(phone);
};

// 获取验证码存储
export const getCodeStore = () => codeStore;
